/*
   Copyright (c) 2020, zoomdy
   MicroAmpereII is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2.
   You may obtain a copy of Mulan PSL v2 at:
            http://license.coscl.org.cn/MulanPSL2
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
   EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
   MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
   See the Mulan PSL v2 for more details.
 */
#include "pt/clock.h"

#include "riscv_encoding.h"
#include "hal_tick.h"

uint32_t hal_tick_get(void)
{
    uint64_t tick_64;
    uint32_t tick_64_lo;
    uint32_t tick_64_hi;
    uint32_t tick_32;

    do {
        tick_64_hi = read_csr(mcycleh);
        tick_64_lo = read_csr(mcycle);
    } while(tick_64_hi != read_csr(mcycleh));

    tick_64 = ((uint64_t)tick_64_hi << 32) | (uint64_t)tick_64_lo;
    tick_32 = tick_64 / 96000;

    return tick_32;
}


clock_time_t clock_time(void)
{
    return hal_tick_get();
}


void hal_tick_delay(uint32_t delay)
{
    uint32_t tick;

    tick = hal_tick_get();
    while(hal_tick_get() - tick < delay) {
    }
}
